package com.atguigu.yygh.order.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowItem;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.utils.AuthContextHolder;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.utils.HttpRequestHelper;
import com.atguigu.yygh.vo.order.OrderCountQueryVo;
import com.atguigu.yygh.vo.order.OrderQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2024-04-15
 */
@Api(tags = "订单接口")
@RestController
@RequestMapping("/api/order/orderInfo")
public class OrderApiController {

    @Autowired
    private OrderInfoService orderInfoService;

    @ApiOperation(value = "创建订单")
    @PostMapping("auth/submitOrder/{hoscode}/{scheduleId}/{patientId}")
    @SentinelResource(value = "submitOrder",blockHandler = "submitOrderBlockHandler")
    public R submitOrder(
            @ApiParam(name = "hoscode", value = "医院编号，限流使用", required = true)
             @PathVariable String hoscode,
            @ApiParam(name = "scheduleId", value = "排班id", required = true)
            @PathVariable String scheduleId,
             @ApiParam(name = "patientId", value = "就诊人id", required = true)
             @PathVariable Long patientId
    ){
        Long orderId = 1L; //orderInfoService.saveOrder(scheduleId,patientId);
        return R.ok().data("orderId",orderId);
    }

    //热点值超过QPS阈值，返回结果
    public R submitOrderBlockHandler(String hoscode, String scheduleId, Long patientId, BlockException e){
        return R.error().message("系统业务繁忙，请稍后下单");
    }

    //订单列表（条件查询带分页）
    @ApiOperation(value = "订单列表")
    @GetMapping("auth/{page}/{limit}")
    public R list(
            @PathVariable Long page,
            @PathVariable Long limit,
            OrderQueryVo orderQueryVo, HttpServletRequest request
            ){
        //设置当前用户id
        orderQueryVo.setUserId(AuthContextHolder.getUserId(request));
        Page<OrderInfo> pageParam = new Page<>(page,limit);
        IPage<OrderInfo> pageModel = orderInfoService.selectPage(pageParam,orderQueryVo);
        return R.ok().data("pageModel",pageModel);
    }

    @ApiOperation(value = "获取订单状态")
    @GetMapping("auth/getStatusList")
    public R getStatusList(){
        return R.ok().data("statusList", OrderStatusEnum.getStatusList());
    }

    //根据订单id查询订单详情
    @GetMapping("auth/getOrders/{orderId}")
    @ApiOperation(value = "根据订单id查询订单详情")
    public R getOrders(@PathVariable Long orderId){
        OrderInfo orderInfo = orderInfoService.getOderInfo(orderId);
        return R.ok().data("orderInfo",orderInfo);
    }

    //取消预约
    @ApiOperation(value = "取消预约")
    @GetMapping("auth/cancelOrder/{orderId}")
    public R cancelOrder(
            @ApiParam(name = "orderId", value = "订单id", required = true)
            @PathVariable("orderId") Long orderId
    ){
        boolean isSuccess  = orderInfoService.cancelOrder(orderId);
        return R.ok().data("flag",isSuccess);
    }

    @ApiOperation(value = "获取订单统计数据")
    @PostMapping("inner/getCountMap")
    public Map<String,Object> getCountMap(@RequestBody OrderCountQueryVo orderCountQueryVo){
        return orderInfoService.getCountMap(orderCountQueryVo);
    }

    //构造方法
    public OrderApiController(){
        initRule();
    }

    /**
     * 导入热点值限流规则
     * 也可以在Sentinel dashboard界面配置（仅配置）
     */
    private void initRule() {
        ParamFlowRule paramFlowRule = new ParamFlowRule("submitOrder")//资源名称，与SentinelResource值保持一致
            //限流第一个参数
            .setParamIdx(0)
            //单机阈值
            .setCount(5);

        //针对 热点参数值单独设置限流QPS阈值，而不是全局的阈值
        //如 1000（北京协和医院），可以通过数据库一次性导入，目前为测试
        ParamFlowItem item = new ParamFlowItem().setObject("1000")//热点值
            .setClassType(String.class.getName())//热点值类型
            .setCount(1);//热点值QPS阈值
        List<ParamFlowItem> list = new ArrayList<>();
        list.add(item);
        paramFlowRule.setParamFlowItemList(list);
        ParamFlowRuleManager.loadRules(Collections.singletonList(paramFlowRule));
    }
}

